package com.wangce.service.impl;

import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wangce.dao.OrderDao;
import com.wangce.entity.Dim;
import com.wangce.entity.Goods;
import com.wangce.entity.Order;
import com.wangce.entity.User;
import com.wangce.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * ClassName: OrderServiceImpl
 * Description:
 * date: 2021/11/11 19:49
 *
 * @author 凡人
 * @since JDK 1.8
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderDao orderDao;

    /**
     * 列表
     * @param d
     * @param cur
     * @param size
     * @return
     */
    @Override
    public PageInfo<Order> list(Dim d, Integer cur, Integer size) {
        PageHelper.startPage(cur,size);
        return new PageInfo<Order>(orderDao.list(d));
    }

    /**
     * 查询对象
     * @param id
     * @return
     */
    @Override
    public Order getOrder(Long id) {
        return orderDao.getOrder(id);
    }

    /**
     * 下单
     *
     * @param user
     * @param order
     * @return
     */
    @Override
    public Integer add(User user, Order order) {
        //生成订单单号
        long l = IdUtil.getSnowflake(31, 31).nextId();
        order.setOrderId(l);
        //添加下单时间
        order.setOrderTime(new Date());
        //添加用户id
        order.setUserId(user.getUserId());
        System.out.println(">>>>>>>>>>>>>>"+order);
        //添加订单
        Integer i = orderDao.add(order);
        //判断商品是否存在
        List<Goods> goods = order.getGoods();
        for (int j = 0; j < goods.size(); j++) {
            if(goods.get(j)!=null){
                //获取商品名称
                String goodsName = goods.get(j).getGoodsName();
                //获取商品对象
                Goods g = orderDao.selectByName(goodsName);
                //判断该商品是否存在
                if(g==null){
                    //该商品不存在,添加商品
                    orderDao.addGoods(goods.get(j));
                    //添加中间表
                    i += orderDao.addOG(order.getOrderId(),goods.get(j).getGoodsId(),goods.get(j).getGoodsNum());
                }else{
                    //添加中间表
                    i += orderDao.addOG(order.getOrderId(),g.getGoodsId(),goods.get(j).getGoodsNum());
                }
            }
        }
        return i;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Override
    public Integer delete(Long id) {
        orderDao.deleteOG(id);
        return orderDao.delete(id);
    }
}
